using System;
using System.Collections.Generic;
using System.Text;

namespace RapidHDL
{
    public class EncodeMap
    {
        System.Collections.Hashtable htMapByCode = new System.Collections.Hashtable();
        System.Collections.Hashtable htMapByName = new System.Collections.Hashtable();

        public int GetUnusedKey()
        {
            int iIdx = 0;
            while (htMapByCode.ContainsKey(iIdx))
                iIdx++;
            return iIdx;
        }

        public void AddCode(string psName)
        {
            AddCode(psName, GetUnusedKey());
        }

        public void AddCode(string psName, int piCode)
        {
            if (htMapByName.ContainsKey(psName))
                System.Diagnostics.Debug.Fail(psName + " is already part of the encode map");

            if (htMapByCode.ContainsKey(piCode))
                System.Diagnostics.Debug.Fail("Code " + piCode.ToString() + " is already part of the encode map");

            htMapByCode.Add(piCode, psName);
            htMapByName.Add(psName, piCode);
        }

        public void AddCode(string psName, string psBinaryCode)
        {
            int iCode = Conversion.StringBinaryToInt(psBinaryCode);
            AddCode(psName, psBinaryCode);
        }

        public int GetCode(string psName)
        {
            if (!htMapByName.ContainsKey(psName))
                System.Diagnostics.Debug.Fail(psName + " is not part of the encode map");

            return (int)htMapByName[psName];
        }

        public string GetCodeBinary(string psName, int piWidth)
        {
            return Conversion.IntToBinaryString(GetCode(psName), piWidth);
        }
    }
}
